<meta charset="UTF-8">

<?php
include_once("../functions/db_manipulate.php");

if (!init()) {
    redirect("../login.php");
}
connectDB();

$uploaddir = $_SERVER['DOCUMENT_ROOT'] . '/user_img/';

switch ($_POST['action']) {
    case 'delete':
        startTransaction();
        $prevImgResultSet = mysql_query("SELECT image FROM users WHERE id=" . $_SESSION['id']) or die(mysql_error());
        $prevPath = mysql_fetch_assoc($prevImgResultSet);
        $prevPath = $uploaddir . $prevPath['image'];
        unlink($prevPath);
        mysql_query("UPDATE users SET image='' WHERE id=" . $_SESSION['id']) or die(mysql_error());
        if ($prevImgResultSet) {
            commitTransaction();
        } else rollbackTransaction();
        break;

    case 'change':
        //Delete previous image
        startTransaction();
        $prevImgResultSet = mysql_query("SELECT image FROM users WHERE id='" . $_SESSION['id'] . "'") or die(mysql_error());
        $prevPath = mysql_fetch_assoc($prevImgResultSet);
        $prevPath = $uploaddir . $prevPath['image'];
        unlink($prevPath);
        echo $prevPath;

        $deleteImgResultSet = mysql_query("UPDATE users SET image='' WHERE id=" . $_SESSION['id'])or die(mysql_error());

        $file = $_SESSION['id'] . "_" . date("dmY") . "_" . date("GHi") . getFormattedTime() . "_user_img" . "." . pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
        $newImg = $uploaddir . $file;

        $addResultSet = null;

        if (move_uploaded_file($_FILES['image']['tmp_name'], $newImg)) {
            $addResultSet = mysql_query("UPDATE users SET image='" . $file . "' WHERE id='" . $_SESSION['id'] . "'")or die(mysql_error());
        } else echo $_FILES['image']['error'];

        if ($addResultSet && $deleteImgResultSet && $prevImgResultSet) {
            commitTransaction();
            echo "success";
        } else rollbackTransaction();

        break;
}

redirect($_SERVER['HTTP_REFERER']);